package com.qinsong.myapplication.controller.activity;

import android.app.Activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.animation.AlphaAnimation;
import android.widget.RelativeLayout;

import com.hyphenate.chat.EMClient;
import com.qinsong.myapplication.R;
import com.qinsong.myapplication.model.Model;
import com.qinsong.myapplication.model.bean.UserInfo;
import com.qinsong.myapplication.utils.ScreenUtils;

/**
 * 欢迎界面
 */
public class SplashActivity extends Activity {
    private Handler handler = new Handler(){
        public void handleMessage(Message msg){
            //如果当前activity已经退出，就不处理
            if(isFinishing()){
                return;
            }
            //判断进入主界面还是登录界面
            toMainOrLogin();
        }
    };
    /**
     * /判断进入主界面还是登录界面
     */
    private void toMainOrLogin() {
       /* new Thread(){
            public void run(){

            }
        }.start();*/
        Model.getInstance().getGlobaThreadPool().execute(new Runnable() {
            @Override
            public void run() {
                //判断当前账号是否已经登录过
                if(EMClient.getInstance().isLoggedInBefore()) {
                    // 获取到当前登录用户的信息
                    UserInfo account = Model.getInstance().getUserAccountDao().getUserInfoByHxId(EMClient.getInstance().getCurrentUser());
                    if (account == null) {
                        // 跳转到登录页面
                        Intent intent = new Intent(SplashActivity.this, LoginActivity.class);
                        startActivity(intent);
                        finish();
                    } else {
                        //登录成功后
                        Model.getInstance().loginSuccess(account);
                        //跳转主页面
                        Intent intent = new Intent(SplashActivity.this, indexActivity.class);
                        startActivity(intent);
                        finish();
                    }
                }else{
                    //加入没登录过，就跳转登录界面
                    Intent intent = new Intent(SplashActivity.this,LoginActivity.class);
                    startActivity(intent);
                    finish();
                }
            }
        });
    }

    @Override
   protected void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.activity_splash);

       //延迟两秒发送延迟消息
        RelativeLayout rootLayout = (RelativeLayout) findViewById(R.id.splash_root);

        AlphaAnimation animation = new AlphaAnimation(0.3f, 1.0f);
        animation.setDuration(1500);
        rootLayout.startAnimation(animation);
       handler.sendMessageDelayed(Message.obtain(),2000);
        ScreenUtils.setFullScreen(this, true);
   }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //销毁消息
        handler.removeCallbacksAndMessages(null);
    }
}
